var num = 1;
var pageSize = 10;
var lastPage = false;

Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
        //return decodeURI(r[2]); //解决中文乱码问题
    }
}

//获取地址栏中的id的值
var paramId = getQueryString("id");

/**
 * 查询协议设计
 */
function listProtocolDesigns(pageNum, pageSize) {
    $.ajax({
        url: HOST.concat("/protocolDesigns/username?username=" + config.username + "&pageNum=" + pageNum + "&pageSize=" + pageSize + "&token=" + config.token),
        type: "GET",
        success: function (datas) {
            checkLogin(datas);
            console.log(datas);
            addContent(datas);
        },
        error: function () {
            console.log("请求设计列表错误！");
        },
        dataType: "json",
    });
}

function addContent(res) {
    //查询成功
    if (res.meta.state === "success") {
        var list = res.data;
        if (list.length == 0) {
            alert("已经是最后一页!");
            num--;
        } else {
            console.log("有查询记录");
            console.log(list);
            $("#tbody").empty();
            $("#pageNum").text(num);
            for (var p in list) {
                //一条数据
                var item = list[p];
                var id = item["id"];
                var protocolName = item["protocolName"];
                var designName = item["designName"];
                var createTime = item["createTime"];
                var designHtml = '<div id="elems" class="tr clearfix border-bottom-none">\
											<div class="td w20">D-' + (id.substr(6, 2) + id.substr(-6)).toUpperCase() + '</div>\
											<div class="td w20">' + protocolName + '</div>\
											<div class="td w20">' + designName + '</div>\
											<div class="td w20">' + createTime + '</div>\
											<div class="td w20">\
												<a href="createConfiguration.html?id=' + id + '" style="color: dodgerblue;">点击选择</a>\
											</div>\
										</div>';
                $("#tbody").append(designHtml);
            }

        }
    } else if (res.meta.message != "notlogin") {
        alert("已经是最后一页!");
        num--;
    }
}


function getProtocolDesigns(num) {
    listProtocolDesigns(num, pageSize);
}

function designLastPage() {
    if (num <= 1) {
        num = 1;
        alert("已经是第一页!");
        $("#pageNum").text(num);
    } else {
        num--;
        getProtocolDesigns(num);
    }
}

function designNextPage() {
    num++;
    getProtocolDesigns(num);
}

function designFirstPage() {
    num = 1;
    $("#pageNum").text(num);
    getProtocolDesigns(num);
}

function dealBtnAttr(btnId) {
    $("#" + btnId).attr("disabled", "disabled");
    $("#" + btnId).css("background-color", "rgb(224,224,224)");
    $("#" + btnId).css("color", "rgb(111,111,111)");
    $("#" + btnId).css("cursor", "default");
}

/**
 * 根据协议设计，显示对应的安全组件配置
 * */
function dealFunctionBtn(res) {
    if (res.meta.state === "success") {
        console.log("有查询记录");

        var designData=res.data;
        //判断用户协议设计选择了哪些安全组件
        if(designData.auth!=null){
            $("#identityConfig").css("display","block");
        }
        if (designData.encrypt!=null) {
            $("#encryptionConfig").css("display","block");
        }
        if (designData.exception!=null) {
            $("#exceptionConfig").css("display","block");
        }
        if (designData.virus!=null) {
            $("#defendConfig").css("display","block");
        }
        if (designData.resend!=null) {
            $("#resendConfig").css("display","block");
        }
        if (designData.integrity!=null) {
            $("#integrityConfig").css("display","block");
        }

    } else {
        alert("查询失败");
        window.location.href = "designProtocol.html";
    }
}

/**
 * 根据协议设计id查找协议设计
 * */
function listDesignFunctions(designId) {
    $.ajax({
        url: HOST.concat("/protocolDesigns/id?id=" + designId + "&token=" + config.token),
        type: "GET",
        success: function (datas) {
            //根据id获取用户协议设计信息成功
            checkLogin(datas);
            //console.log(datas);
            dealFunctionBtn(datas);
        },
        error: function () {
            console.log("请求功能项错误！");
        },
        dataType: "json",
    });
}

/**
 * 配置参数变量
 */
var Encrypt = function (algorithm, mode, output, range) {
    this.algorithm = algorithm;
    this.mode = mode;
    this.output = output;
    this.range = range;
}
var Exception = function (method) {
    this.method = method;
}
var Virus = function (method) {
    this.method = method;
}
var Resend = function (queue, time, count) {
    this.queue = queue;
    this.time = time;
    this.count = count;
}
var Integrity = function (algorithm) {
    this.algorithm = algorithm;
}

var encrypt = new Encrypt();
var exception = new Exception();
var virus = new Virus();
var resend = new Resend();
var integrity = new Integrity();

/**
 * 获取用户输入或选择的协议配置信息
 */
function getConfigInfo(data) {

    var authType=$("#identityConfig option:selected").val();
    data.authType=authType;

    if ($("#encryptionConfig").css("display") == "block") {
        //xxxxx.css("display") == "block" 意味着用户选择了对应的安全组件
        encrypt.algorithm = $("#encryptAlgorithm option:selected").val();
        encrypt.mode = $("#encryptMode option:selected").val();
        encrypt.output = $("#encryptOutput option:selected").val();
        encrypt.range = $("#encryptRange option:selected").val();
        data.encrypt = encrypt;
    }else{
        data.encrypt=null;
    }

    if ($("#exceptionConfig").css("display") == "block") {
        exception.method = $("#exceptionMethod option:selected").val();
        data.exception = exception;
    }else{
        data.exception=null;
    }

    if ($("#defendConfig").css("display") == "block") {
        virus.method = $("#virusMethod option:selected").val();
        data.virus = virus;
    }else{
        data.virus =null;
    }

    if ($("#resendConfig").css("display") == "block") {
        resend.queue = $("#resendQueue option:selected").val();
        resend.time = $("#timeInput").val();
        resend.count = $("#resendCount option:selected").val();
        data.resend = resend;
    }else{
        data.resend=null;
    }

    if ($("#integrityConfig").css("display") == "block") {
        integrity.algorithm = $("#integrityAlgorithm option:selected").val();
        data.integrity = integrity;
    }else{
        data.integrity =null;
    }
}

/**
 * 保存配置信息
 */
function saveConfigInfo() {

    var data = {};
    data.designId = paramId;
    //检查输入是否规范
    if (checkTimeInput() == true) {
        $("#saveConfig").attr('disabled',true);
        //获取用户输入和选择的数据
        getConfigInfo(data);

        $.ajax({
            url: HOST.concat("/protocolConfigs?token=" + config.token),
            type: "POST",
            data: JSON.stringify(data),
            contentType: "application/json",
            success: function (datas) {
                $("#saveConfig").attr('disabled',false);
                checkLogin(datas);
                if (datas.meta.state === "success") {
                    $("#saveConfig").attr('disabled',false);
                    alert("保存成功!");
                    //协议配置完直接跳转到设计列表
                    window.location.href="designProtocol.html";
                } else {
                    alert("保存失败!");
                }
            },
            error: function () {
                console.log("请求保存配置信息错误！");
            },
            dataType: "json",
        });
    }

}

/**
 * 检查通信重传的input框输入是否规范
 * */
function checkTimeInput() {

    if ($("#resendConfig").css("display") == "block") {
        //只有在之前设计部分选择了通信重传这里才会检查"重传时间"有没有填入
        var time = $("#timeInput").val();
        if (time != '' && time != undefined) {
            var reg = /^[0-9]{1,2}([.]{1}[0-9]{1,3}){0,1}$/;
            if (reg.test(time) != true) {
                alert("重传超时时间输入不规范");
                return false;
            }else if(time>30){
                alert("重传时间不能超过30ms！");
                return false;
            } else {
               if(time==0){
                    alert("重传时间不能为 0");
                    return false;
                }else{
                    var t = parseFloat(time);
                    $("#timeInput").val(t.toFixed(3));
                    return true;
                    }
            }
        } else {
            alert("重传超时时间不能为空");
            return false;
        }
    }else{
        return true;
    }


}
